using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

public class BloomPostProcessRendererFeature : ScriptableRendererFeature
{
    [System.Serializable]
    public class BloomSettings
    {
        public RenderPassEvent renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing;
        public Material bloomMaterial = null;
        [Range(0.0f, 0.1f)] public float bloomSize = 0.01f;
        [Range(0.0f, 5.0f)] public float bloomIntensity = 1.0f;
        [Range(0.0f, 1.0f)] public float bloomThreshold = 0.4f;
        [Range(1.0f, 3.0f)] public float bloomGamma = 2.0f;
    }

    public BloomSettings settings = new BloomSettings();

    class BloomPass : ScriptableRenderPass
    {
        private Material m_BloomMaterial;
        // private RenderTargetIdentifier m_Source; // <- 移除
        private RenderTargetHandle m_TemporaryColorTexture;

        private string m_ProfilerTag;
        private BloomSettings m_Settings;

        public BloomPass(string profilerTag, BloomSettings settings)
        {
            m_ProfilerTag = profilerTag;
            m_Settings = settings;
            m_BloomMaterial = settings.bloomMaterial;
            m_TemporaryColorTexture.Init("_TemporaryColorTexture");
        }

        // 移除 Setup 方法
        // public void Setup(RenderTargetIdentifier source)
        // {
        //     this.m_Source = source;
        // }

        public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
        {
            // 不需要配置
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);

            if (m_BloomMaterial == null)
            {
                Debug.LogErrorFormat("Bloom Material is missing for {0}. Can't execute the pass.", m_ProfilerTag);
                CommandBufferPool.Release(cmd);
                return;
            }

            // 检查相机是否配置为渲染到纹理，如果是，则可能跳过后处理
            if (renderingData.cameraData.isSceneViewCamera) // 可选：不在 Scene 视图应用
                 //return;
            if (renderingData.cameraData.isPreviewCamera) // 可选：不在预览窗口应用
                 //return;


            m_BloomMaterial.SetFloat("_BloomSize", m_Settings.bloomSize);
            m_BloomMaterial.SetFloat("_BloomIntensity", m_Settings.bloomIntensity);
            m_BloomMaterial.SetFloat("_BloomThreshold", m_Settings.bloomThreshold);
            m_BloomMaterial.SetFloat("_BloomGamma", m_Settings.bloomGamma);

            RenderTextureDescriptor opaqueDesc = renderingData.cameraData.cameraTargetDescriptor;
            opaqueDesc.depthBufferBits = 0;

            // !! 在 Execute 内部获取 cameraColorTarget !!
            var cameraColorTarget = renderingData.cameraData.renderer.cameraColorTarget;

            // 创建临时 RT
            cmd.GetTemporaryRT(m_TemporaryColorTexture.id, opaqueDesc, FilterMode.Bilinear);

            // Blit 源 (相机目标) 到临时 RT
            // Blit(cmd, m_Source, m_TemporaryColorTexture.Identifier()); // <- 旧代码
            Blit(cmd, cameraColorTarget, m_TemporaryColorTexture.Identifier()); // <- 新代码

            // Blit 临时 RT 回源 (相机目标)，应用材质
            // Blit(cmd, m_TemporaryColorTexture.Identifier(), m_Source, m_BloomMaterial, 0); // <- 旧代码
            Blit(cmd, m_TemporaryColorTexture.Identifier(), cameraColorTarget, m_BloomMaterial, 0); // <- 新代码

            context.ExecuteCommandBuffer(cmd);
            cmd.ReleaseTemporaryRT(m_TemporaryColorTexture.id);
            CommandBufferPool.Release(cmd);
        }

        public override void FrameCleanup(CommandBuffer cmd)
        {
           // 不需要显式清理 m_TemporaryColorTexture.id，因为它在 Execute 中已释放
        }
    }

    BloomPass m_BloomPass;

    public override void Create()
    {
        if (settings.bloomMaterial == null)
        {
            Debug.LogWarning("Bloom Material is not assigned in BloomPostProcessRendererFeature. Effect will not render.");
            // 确保即使材质为空也不创建 Pass，或者提供默认材质
             // return; // 如果没有材质，可以选择不创建 Pass
        }
         // 即使材质为空也创建 Pass，但在 Execute 中检查
        m_BloomPass = new BloomPass("Bloom PostProcess", settings);
        m_BloomPass.renderPassEvent = settings.renderPassEvent;
    }

    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
    {
        // 材质检查移到 Execute 中，这里只负责入队
        if (m_BloomPass == null) // 确保 Pass 已创建
        {
             if (settings.bloomMaterial != null) // 如果材质后来被赋值了，尝试重新创建
             {
                Create(); // 尝试重新创建 Pass
                if(m_BloomPass == null) return; // 如果还是失败则返回
             } else {
                return; // 没有材质且 Pass 未创建，则不添加
             }
        }


        // !! 移除获取 src 和调用 Setup 的代码 !!
        // var src = renderer.cameraColorTarget; // <- 移除 (Line 131)
        // m_BloomPass.Setup(src); // <- 移除 (Line 132)

        renderer.EnqueuePass(m_BloomPass);
    }
}